<?php
namespace lactone\Core\Models;

use ActiveRecord\Model;
use lactone\Core\data\SocketData;

class TaskModel extends Model{

    const Wait_Status      = 0;  //等待执行任务
    const Wait_Next_Status = 1;  //下一次执行的任务
    const Working_Status   = 2;  //执行中的任务
    const Success_Status   = 3;  //完成的任务
    const Fail_Status      = 4;  //执行错误的任务4

    static $status_list = [
        self::Wait_Status      => '等待执行任务',
        self::Wait_Next_Status => '任务下一次执行',
        self::Working_Status   => '任务开始执行',
        self::Success_Status   => '任务执行成功',
        self::Fail_Status      => '任务执行失败'
    ];

    static $after_create = array('task_log_create_task');
    static $after_update = array('task_log_update_task');

    static $table = 'task';

    static $before_create = [
        'inject_time'
    ];

    static $before_save   = [
        'inject_update_time'
    ];

    /**
     * 插入数据时候自动插入时间
     * @return bool
     */
    public function inject_time(){
        $this->update_at = $this->create_at = time();
        return true;
    }

    /**
     * 更新数据时自动更新
     * @return bool
     */
    public function inject_update_time(){
        $this->update_at = time();
        return true;
    }



    public function __toString(){
        $Sock = new SocketData();

         $Sock->create([
            'id'        => $this->id,
            'url'       => $this->url,
            'request'   => unserialize($this->request)
        ],'task');

        return $Sock->__toString();
    }

    /**
     * 创建日志的时候创建任务生成日志
     */
    public function task_log_create_task(){
        $Content = '任务新建成功';
        if($this->p_id){
            $Content.= ",父任务:".$this->p_id;
        }
        TasklogModel::create(['task_id'=>$this->id,'action'=>TasklogModel::ACTION_CREATE,'content'=>$Content]);
    }

    /**
     * 更新日志的时候创建任务更新日志
     */
    public function task_log_update_task(){
        $Content = '任务更新';
        $Content.= ',状态:'.self::$status_list[$this->status];

        TasklogModel::create(['task_id'=>$this->id,'action'=>TasklogModel::ACTION_UPDATE,'content'=>$Content]);
    }

    /**
     * 当前数据库是否为空
     */
    public static function is_empty(){
        if($has = self::find('last')){
            return false;
        }
        return true;
    }

    /**
     * 根据url和request创建hash
     * @param $url
     * @param $request
     */
    public static function create_hash($url,$request){

        if(isset($request['Referer'])){
           unset($request['Referer']);
        }

        return md5(json_encode([
            'url'       => $url,
            'request'   => $request
        ]));

    }

    public static function hasTask($hash){
        if($task = self::find(['hash'=>$hash])){
            return true;
        }
        return false;
    }
}